package com.neusoft.bizcore.activiti.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.neusoft.bizcore.activiti.dto.ProcessFormItemDTO;
import com.neusoft.bizcore.activiti.model.ProcessFormItem;
import com.neusoft.bizcore.activiti.repository.ProcessFormItemRepository;
import com.neusoft.bizcore.activiti.repository.ProcessFormRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class ProcessFormItemConverter extends AbstractConverter<ProcessFormItem, ProcessFormItemDTO> {

    @Autowired
    private ProcessFormItemRepository processFormItemRepository;
    @Autowired
    private ProcessFormRepository processFormRepository;

    @Override
    public ProcessFormItem toModel(final ProcessFormItemDTO dto) {

        ProcessFormItem model;

        if (dto.isNew()) {
            model = new ProcessFormItem();
        } else {
            model = this.processFormItemRepository.getOne(dto.getId());
        }

        model.setNodeKey(dto.getNodeKey());
        model.setName(dto.getName());

        if (!StringUtils.isEmpty(dto.getFormCode())) {
            model.setForm(this.processFormRepository.findByCode(dto.getFormCode()));
        }
        return model;
    }

    @Override
    public ProcessFormItemDTO toDTO(final ProcessFormItem model, final boolean forListView) {

        final ProcessFormItemDTO dto = new ProcessFormItemDTO();

        dto.setId(model.getId());
        dto.setNodeKey(model.getNodeKey());
        dto.setName(model.getName());

        return dto;
    }

}
